
#import "KKScanningView.h"

@interface KKScanningView() <AVCaptureMetadataOutputObjectsDelegate> {
    
    AVCaptureSession *_captureSession;
}

@end

@implementation KKScanningView

- (instancetype)init {
    
    //获取摄像设备
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType: AVMediaTypeVideo];
    if (device == nil) {
        //  设备不支持调用摄像头
        return nil;
    }
    
    CGFloat rootViewWidth = CGRectGetWidth([[UIScreen mainScreen] bounds]);
    CGFloat rootViewHeight = CGRectGetHeight([[UIScreen mainScreen] bounds]);
    
    self = [super initWithFrame: CGRectMake(0, 0, rootViewWidth, rootViewHeight)];
    if (self) {
        
        CGFloat pointX = (CGRectGetWidth(self.bounds) - 280)/2;
        CGFloat pointY = 180;
        CGFloat width = 280.0;
        CGFloat height = 280.0;
        
        if (device == nil) {
        }
        //创建输入流
        AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
        //创建输出流
        AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
        
        float pointXRatio = pointX / rootViewWidth;
        float pointYRatio = pointY / rootViewHeight;
        float widthRatio = width / rootViewWidth;
        float heightRatio = height / rootViewHeight;
        
        output.rectOfInterest = CGRectMake(pointYRatio, pointXRatio, heightRatio, widthRatio);
        
        //设置代理 在主线程里刷新
        [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        
        //初始化链接对象
        _captureSession = [[AVCaptureSession alloc]init];
        //高质量采集率
        [_captureSession setSessionPreset:AVCaptureSessionPresetHigh];
        
        [_captureSession addInput:input];
        [_captureSession addOutput:output];
        //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
        output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeCode39Code];
        
        AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession: _captureSession];
        layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
        layer.frame=self.layer.bounds;
        
        [self.layer insertSublayer:layer atIndex:0];
        
        [self initBackgroundViewWithRect: CGRectMake(pointX, pointY, width, height)];
        
    }
    return self;
}

- (void)initBackgroundViewWithRect:(CGRect)rect {
    
    UIColor *backgroundColor = [UIColor colorWithWhite:0.000 alpha:0.500];
    
    UIView *topView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetMinY(rect))];
    topView.backgroundColor = backgroundColor;
    [self addSubview: topView];
    
    UIView *bottomView = [[UIView alloc] initWithFrame: CGRectMake(0, CGRectGetMaxY(rect), CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) - CGRectGetMaxY(rect))];
    bottomView.backgroundColor = backgroundColor;
    [self addSubview: bottomView];
    
    UIView *leftView = [[UIView alloc] initWithFrame: CGRectMake(0, CGRectGetMinY(rect), CGRectGetMinX(rect), CGRectGetHeight(rect))];
    leftView.backgroundColor = backgroundColor;
    [self addSubview: leftView];
    
    UIView *rightView = [[UIView alloc] initWithFrame: CGRectMake(CGRectGetMaxX(rect), CGRectGetMinY(rect), CGRectGetWidth(self.bounds) - CGRectGetMaxX(rect), CGRectGetHeight(rect))];
    rightView.backgroundColor = backgroundColor;
    [self addSubview: rightView];
    
    UIImageView *imageView1 = [[UIImageView alloc] initWithFrame: CGRectMake(CGRectGetMinX(rect), CGRectGetMinY(rect), 16, 16)];
    imageView1.image = [UIImage imageNamed: @"ScanQR1"];
    [self addSubview: imageView1];
    
    UIImageView *imageView2 = [[UIImageView alloc] initWithFrame: CGRectMake(CGRectGetMaxX(rect) - 16, CGRectGetMinY(rect), 16, 16)];
    imageView2.image = [UIImage imageNamed: @"ScanQR2"];
    [self addSubview: imageView2];
    
    UIImageView *imageView3 = [[UIImageView alloc] initWithFrame: CGRectMake(CGRectGetMinX(rect), CGRectGetMaxY(rect) - 16, 16, 16)];
    imageView3.image = [UIImage imageNamed: @"ScanQR3"];
    [self addSubview: imageView3];
    
    UIImageView *imageView4 = [[UIImageView alloc] initWithFrame: CGRectMake(CGRectGetMaxX(rect) - 16, CGRectGetMaxY(rect) - 16, 16, 16)];
    imageView4.image = [UIImage imageNamed: @"ScanQR4"];
    [self addSubview: imageView4];
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate methods

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects.count>0) {
        //[session stopRunning];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
        //输出扫描字符串
        NSLog(@"%@",metadataObject.stringValue);
        NSString *result = metadataObject.stringValue;
        if (result && _resultHandle) {
            [_captureSession stopRunning];
            _resultHandle(result);
        }
    }
}

#pragma mark - 

- (void)startScanning {
    
    [_captureSession startRunning];
}

- (void)stopScanning {
    
    [_captureSession stopRunning];
}

@end
